package com.demo.book_manage.Service;

import com.demo.book_manage.DAO.BookDAO;
import com.demo.book_manage.POJO.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * book的业务逻辑层
 *
 * @author 梁灿鑫
 * @since 2021-01-28
 */
@Service
@Transactional
public class BookService {
    @Autowired
    private BookDAO bookDAO;

    //保存单本书籍
    public void saveBook(Book book){
        bookDAO.save(book);
    }

    //删除单本书籍（通过ID）
    public void deleteBookById(long id){
        if(bookDAO.findById(id).isPresent()){
            bookDAO.deleteById(id);
        }
    }

    //删除单本书籍（通过书名）
    public void deleteBookByName(String name){
        if((!"".equals(bookDAO.findBookByName(name)))||bookDAO.findBookByName(name)!=null){
            bookDAO.removeBookByName(name);
        }
    }

    //修改书籍信息
    public void modifyBook(Book book, long id){
        if(bookDAO.findById(id).isPresent()){
            Book modifyBook = bookDAO.findById(id).get();
            modifyBook.setName(book.getName());
            modifyBook.setPrice(book.getPrice());
            bookDAO.saveAndFlush(modifyBook);
        }
    }

    //查询单本书籍（通过书名）
    public List<Book> findBookByName(String name){
        List<Book> books = new ArrayList<>();
        if((!"".equals(bookDAO.findBookByName(name)))||(bookDAO.findBookByName(name)!=null)){
            books = bookDAO.findBookByName(name);
        }
        return books;
    }

    //查询单本书籍（通过id）
    public Book findBookById(long id){
        Book book = null;
        if(bookDAO.findById(id).isPresent()){
            book = bookDAO.findById(id).get();
        }
        return book;
    }

    //查询所有书籍
    public List<Book> findAllBooks(){
        return new ArrayList<>(bookDAO.findAll());
    }

}
